package com.weipai.education.config.interceptor;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author songmengqiang
 * @create 2018-09-17 12:47
 **/
@Aspect
@Component
public class WebLogInterceptor {

    private static Logger logger = LoggerFactory.getLogger(WebLogInterceptor.class);
    @Pointcut("execution(public * com.weipai.education.controller..*.*(..))")
    public void controllerMethod() {
    }
    @Pointcut("execution(public * com.weipai.education.service.impl..*.*(..))")
    public void serviceMethod() {

    }

    @Pointcut("execution(public * com.weipai.education.dao.impl..*.*(..))")
    public void daoMethod() {

    }

    @Before("controllerMethod()")
    public void doIntoController(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String clz = joinPoint.getTarget().getClass().getSimpleName();
        String method = joinPoint.getSignature().getName();
        MDC.put("traceId", System.currentTimeMillis() + "");
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("{}.{} param{}", clz, method, Arrays.toString(joinPoint.getArgs()));
    }

    @Before("serviceMethod()")
    public void doIntoService(JoinPoint joinPoint) {
        String clz = joinPoint.getTarget().getClass().getSimpleName();
        logger.info("{}.{} param{}", clz, joinPoint.getClass().getName(), Arrays.toString(joinPoint.getArgs()));
    }

    @Before("daoMethod()")
    public void doIntoDao(JoinPoint joinPoint) {
        String clz = joinPoint.getTarget().getClass().getSimpleName();
        logger.info("{}.{} param{}", clz, joinPoint.getClass().getName(), Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", value = "controllerMethod()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) {
        String clz = joinPoint.getTarget().getClass().getSimpleName();
        String method = joinPoint.getSignature().getName();
        logger.info("{}.{} end response={}", clz, method, JSON.toJSONString(ret));
        MDC.remove("traceId");
    }
}
